import sys, os, re, datetime
import xbmc, xbmcgui, xbmcaddon
import urllib, urllib2, cookielib
import threading

# sys.path.append('C:\Python27\Lib\ctypes')
# sys.path.append('C:\Python27\Lib\site-packages')
sys.path.append('C:\Program Files\XBMC\system\python\Lib\site-packages')
# sys.path.append('C:\Python27\libs')
import serial

print '=' * 100

# Script constants
__scriptname__ = "VPLAY"
__author__     = "user"
__url__        = ""
__credits__    = ""
__version__    = "1.0.0"
__settings__   = xbmcaddon.Addon(id='script.vplay')
__cwd__        = __settings__.getAddonInfo('path')
__test__       = (__settings__.getSetting('testmode') == 'true')
__test_vid__   = ['D:\\Fill Me\\House S01E01.avi', 'D:\\Fill Me\\House S01E01.srt']
__vdata__      = {}
__ser__        = serial.Serial(port='COM2', baudrate=9600, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE)

print "[SCRIPT] '%s: version %s' initialized!" % (__scriptname__, __version__, )


class position:
	def __init__(self):
		self.List = {}
		self._load()
		
	def _load(self):
		p = __settings__.getSetting('pos')
		if(len(p)>0):
			positions = re.compile('(.+?)\[(.+?)\]').findall(p)
			for id, pos in positions:
				print 'Video [%s] was stopped at [%s]' % (id, pos)
				self.List[ id ] = pos

	def _save(self):
		p = ''
		if (len(self.List)>0):
			for id in self.List:
				p = p + id + '[' + self.List[ id ] + ']'
			print 'Stored positions : "%s"' % p
		else:
			print 'Positions list is empty.'
		__settings__.setSetting('pos', p)

	def getPosition(self, id):
		if id in self.List:
			result = self.List[ id ]
		else:
			result = ''
		return result

	def setPosition(self, id, value):
		if len(value)>0:
			self.List[ id ] = value
		elif id in self.List:
			del self.List[ id ]
		self._save()

	def delPosition(self, id):
		if id in self.List:
			print 'Removing [%s] from positions list' % id
			del self.List[ id ]
		self._save()


class favlist:
	def __init__(self):
		self.List = {}
		self._load()

	def _load(self):
		l = __settings__.getSetting('favlist')
		print l
		if (len(l)>0):
			favs = re.compile('(.+?)\[(.+?)\]').findall(l)
			for fav_id, fav_name in favs:
				print 'Fav [%s] : [%s]' % (fav_id, fav_name)
				self.List[ fav_id ] = fav_name

	def _save(self):
		l = ''
		if (len(self.List)>0):
			for fav in self.List:
				l = l + fav + '[' + self.List[ fav ] + ']'
			print 'Fav list : "%s"' % l
			__settings__.setSetting('favlist', l)

	def getFav(self, id):
		if id in self.List:
			return True
		else:
			return False

	def setFav(self, id, name):
		self.List[ id ] = name
		self._save()

	def delFav(self, id):
		if id in self.List:
			del self.List[ id ]
			self._save()


class vplayer(xbmc.Player):
	def __init__(self, *args, **kwargs):
		xbmc.Player.__init__(self)
		self.SleepTimer = 1000
		self.vid = kwargs['vid']
		self.subs = kwargs['subs']
		self.video_id = kwargs['id']
		self.item = kwargs['listitem']
		self.elapsed_time = ''
		self.total_time = ''

		self.last_pos_list = {'0':30, '1':60, '2':90, '3':120, '4':180, '5':240, '6':300}
		self.step_back_list = {'0':0, '1':5, '2':10, '3':30, '4':60, '5':120}
		self.last_pos = 90
		self.step_back = 5
		self.last_pos_id = __settings__.getSetting('last_pos')
		self.step_back_id = __settings__.getSetting('step_back')

		if len(self.last_pos_id)>0:
			if self.last_pos_id in self.last_pos_list:
				self.last_pos = self.last_pos_list[ self.last_pos_id ]

		if len(self.step_back_id)>0:
			if self.step_back_id in self.step_back_list:
				self.step_back = self.step_back_list[ self.step_back_id ]

		if (len(self.vid)>0):
			print 'Playing [%s]' % self.vid
			self.active = 1
			if len(__vdata__)>0:
				i = xbmcgui.ListItem()
				print 'Video data : [%s]' % str(__vdata__)
				i.setInfo('video', __vdata__)
				i.setPath(self.vid)
				if not __test__:
					i.setIconImage(__htm__.VideoThumbnail)
					i.setThumbnailImage(__htm__.VideoThumbnail)
				else:
					i.setIconImage('D:\\logo.jpg')
					i.setThumbnailImage('D:\\logo.jpg')
				self.play(self.vid, i)
			else:
				print 'No video data available.'
				self.play(self.vid)

		self._waitForPlaybackCompleted()

	def __del__(self):
		print '*' * 100

	def onPlayBackStarted(self):
		print '-=' * 50
		print 'Playback STARTED.'
		try:
			self.total_time = str(self.getTotalTime()).split('.')[0]
			print 'Video length : %s sec.' % self.total_time
		except:
			print 'getTotalTime() EXCEPTION : Player is not playing anything!'
		
		if (len(self.video_id)>0):
			self.elapsed_time = __pos__.getPosition(self.video_id)
			if( len(self.elapsed_time)>0 ):
				f = float(self.elapsed_time) - self.step_back
				if( f > 0 ):
					print 'Skipping to [%s] sec. and stepping back [%s] sec.' % (self.elapsed_time, str(self.step_back))
					self.seekTime( f )
				else:
					print 'Step back time exceeds elapsed time. Playing from start.'

		if (len(self.subs)>0):
			for lang in self.subs:
				print 'Adding subtitle : [%s] - [%s]' % (lang, self.subs[lang])
				self.setSubtitles(self.subs[lang])
		
		self.active = 2

	def onPlayBackEnded(self):
		print '-=' * 50
		print 'Playback ENDED.'
		if (len(self.video_id)>0):
			__pos__.delPosition(self.video_id)
		self.active = 0

	def onPlayBackStopped(self):
		print '-=' * 50
		print 'Playback STOPPED.'
		print 'Elapsed : %s seconds.' % self.elapsed_time
		if (len(self.video_id)>0):
			try:
				delta_t = int(self.total_time) - int(self.elapsed_time)
				print 'Time from end : %s sec.' % str(delta_t)
				if delta_t > self.last_pos:
					print 'Saving pos.'
					__pos__.setPosition(self.video_id, self.elapsed_time)
				else:
					print 'Position exceeded delta.'
					__pos__.delPosition(self.video_id)
			except:
				print 'Something be wrong!'
				__pos__.setPosition(self.video_id, self.elapsed_time)
		self.active = 0

	def _waitForPlaybackCompleted(self):
		while (self.active > 0):
			if (self.active > 1):
				try:
					self.elapsed_time = str(self.getTime()).split('.')[0]
				except:
					print 'getTime() EXCEPTION : Player is not playing anything!'
			xbmc.sleep(self.SleepTimer)


class htm:
	def __init__(self):
		print 'Initializing HTML interface'
		self.testmode = __settings__.getSetting('testmode')
		self.CookieFile = __cwd__ + '\\cookies.lwp'
		self.username = ''
		self.password = ''
		self.Page = ''
		self.Url = ''
		self.Code = 0
		self.Subtitles = {}
		self.VideoId = ''
		self.VideoUrl = ''
		self.VideoLabel = ''
		self.VideoThumbnail = ''
		self.UserID = ''
		self.UserDays = ''
		self.UserAvatar = ''
		self.urlopen = urllib2.urlopen
		self.Request = urllib2.Request
		self.cj = cookielib.LWPCookieJar()
		if os.path.isfile(self.CookieFile):
			self.cj.load(self.CookieFile)
			print 'Cookies loaded!'
		self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cj))
		urllib2.install_opener(self.opener)
		
		if not __test__:
			if ( self.getPage( url='http://www.vplay.ro', txdata=None ) ):
				pass
			else:
				self.Login()
		else:
			pass

	def Login(self):
		print 'Logging in ...'
		self.username = __settings__.getSetting('username')
		self.password = __settings__.getSetting('password')
		data = urllib.urlencode({'rtr': '', 'username': self.username, 'pwd': self.password, 'remember_me': '1', 'login': 'Conectare'})
		self.getPage( url='http://www.vplay.ro/login/', txdata=data )
		usr = self.user(self.Page)
		if (len(usr) > 0):
			print 'Login SUCCESSFUL for user [%s]' % usr
		else:
			print 'Login FAILED!'
		self.cj.save(self.CookieFile)
		return (len(usr) > 0)
		
	def getPage(self, url, txdata):
		if __test__:
			wpage = open(url)
			self.Page = wpage.read()
			wpage.close()
			self.Code = 200
			self.Url = url
		else:
			txheaders =  {'User-agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'}
			req = self.Request(url, txdata, txheaders)
			handle = self.urlopen(req)
			self.Page = handle.read()
			self.Code = handle.code
			self.Url = handle.geturl()
		usr = self.user(self.Page)
		print 'Page : [%s] User  : [%s]' % (url, self.user(self.Page))
		# f = open(__cwd__ + '\\_page.htm', 'w')
		# f.write(self.Page)
		# f.close()
		return (len(usr) > 0)
		
	def getVideo(self, id):
		print '+-' * 60
		self.Subtitles = {}
		self.VideoId = id
		self.VideoUrl = ''
		self.VideoLabel = ''
		if __test__:
			wpage = open(__cwd__ + '\\samples\\player.htm')
			self.Page = wpage.read()
			wpage.close()
		else:
			self.getPage( url='http://www.vplay.ro/watch/' + id + '/', txdata=None )
		data1 = re.compile('tv-link-top">(.+?)<').findall(self.Page)
		data2 = re.compile('tv-txt-top">(.+?)<').findall(self.Page)
		data = data1 + data2
		label = ''
		__vdata__.clear()
		if (len(data)>0):
			__vdata__['tvshowtitle'] = data[1]
			__vdata__['season'] = int(data[2].split(' ')[1])
			__vdata__['episode'] = int(data[3].split(' ')[1])
			label = data[1] + ' ' + data[2].split(' ')[1] + 'x' + data[3].split(' ')[1]
			if (len(data)>4):
				label = label + ' ' + data[4]
				__vdata__['title'] = data[4]
			else:
				__vdata__['title'] = ' '
		else:
			label = id
		print 'Video label : [%s]' % label
		self.VideoLabel = label
		serie_id = re.compile('browse.do\?sid=(.+?)"').findall(self.Page)
		if len(serie_id)>0:
			img = 'http://i.vplay.ro/ch/' + serie_id[0] + '.jpg'
			print 'Logo image : [%s]' % img
			self.VideoThumbnail = img
		if not __test__:
			self.getPage( url='http://www.vplay.ro/play/dinosaur.do', txdata=urllib.urlencode({'onLoad':'%5Btype%20Function%5D', 'external':'0', 'key':id}) )
			if (len(self.Page)>0):
				url = re.compile('URL=(.+?)&').findall(self.Page)
				self.VideoUrl = url[0]
				all_subs = re.compile('subs=\[(.+?)\]').findall(self.Page)
				print 'Real URL  : [%s]' % url[0]
				
				if (len(all_subs)>0):
					filename = __cwd__ + '\\subs\\' + label
					if os.path.isfile( filename + '.RO.srt' ):
						print 'Subtitle [RO] already exists.' 
						self.Subtitles[ 'RO' ] = filename + '.RO.srt'
					elif (all_subs[0].find('RO')>0):
						self.SubToFile( lang='RO', fname=filename + '.RO.srt' )
						self.Subtitles[ 'RO' ] = filename + '.RO.srt'
					elif os.path.isfile(filename + '.EN.srt'):
						print 'Subtitle [EN] already exists.' 
						self.Subtitles[ 'EN' ] = filename + '.EN.srt'
					elif (all_subs[0].find('EN')>0):
						self.SubToFile( lang='EN', fname=filename + '.EN.srt' )
						self.Subtitles[ 'EN' ] = filename + '.EN.srt'
		else:
			self.VideoUrl = 'D:\\1.avi'
			self.Subtitles['RO'] = 'D:\\2.srt'

	def getUserData(self):
		if len(self.Page)>0:
			id = re.compile('class="username">(.+?)<').findall(self.Page)
			if len(id)>0:
				self.UserID = id[0]
			if __test__:
				self.UserAvatar = 'D:\\avatar.jpg'
			else:
				avatar = re.compile('class="avatar"><img src="(.+?)"').findall(self.Page)
				if len(avatar)>0:
					self.UserAvatar = avatar[0]
			days = re.compile('noti-number vipdays">(.+?)<').findall(self.Page)
			if len(days)>0:
				self.UserDays = days[0]
			if len(self.UserID)>0:
				print 'User: [%s] VIP days : [%s] Avatar : [%s]' % (self.UserID, self.UserDays, self.UserAvatar)
			else:
				print 'No user data available.'

	def SubToFile(self, lang, fname):
		print 'Downloading subtitle [%s] and parsing into file [%s]' % (lang, fname)
		self.getPage( url='http://www.vplay.ro/play/subs.do', txdata=urllib.urlencode({'onLoad':'%5Btype%20Function%5D', 'sc':'undefined', 'lang':lang, 'key':self.VideoId}) )
		if (len(self.Page))>0:
			new_sub = self.parse_sub(self.Page)
			f = open(fname, 'w')
			f.write(new_sub)
			f.close()
		else:
			print 'Error downloading subtitle [%s]' % lang

	def getCookieFile(self):
		return self.CookieFile

	def user(self, page):
		usr = re.compile('class="username">(.+?)</a>').findall(page)
		if len(usr)>0: 
			return str(usr[0])
		else: 
			return ''

	def video_id(self, page):
		vid = re.compile('"key", "(.+?)"').findall(page)
		if len(vid)>0: 
			return str(vid[0])
		else: 
			return 'None'

	def parse_sub(self, sub):
		result = ''
		if (len(sub)>0):
			lines = re.compile('{"s":"(.+?)",.*?"f":(.+?),.*?"t":(.+?)}').findall(sub)
			index = 1
			if (len(lines)>0):
				for s, f, t in lines:
					dt1 = datetime.datetime(1970,1,1) + datetime.timedelta(seconds = int(f))
					dt2 = datetime.datetime(1970,1,1) + datetime.timedelta(seconds = int(t))
					result = result + str(index) + '\n' + dt1.strftime('%H:%M:%S,100') + ' --> ' + dt2.strftime('%H:%M:%S,000') + '\n'
					for ln in s.split('<br>'):
						result = result + ln + '\n'
					result = result + '\n'
					index = index + 1
			else:
				print 'Parsing ERROR : Invalid subtitle data!'
		else:
			print 'Parsing ERROR : subtitle stream empty!'
		return result


__htm__ = htm()
__fav__ = favlist()
__pos__ = position()

test_vid_file = 'D:\\Fill Me\\House S01E01.avi'
test_sub_file = 'D:\\Fill Me\\House S01E01.srt'

# test = vplayer( xbmc.PLAYER_CORE_AUTO, vid=test_vid_file, subs={'RO':test_sub_file}, id='test2' )
__ser__.write('Hello, world - from XBMC!\n')

if (__name__ == "__main__"):
    import resources.lib.Start as Start
    page_start = Start.GUI("vplay_start.xml", __cwd__, "default", setNum = 'set1')
    del page_start

print '-' * 100
print "[SCRIPT] '%s: version %s' exited." % (__scriptname__, __version__, )
__ser__.close()
sys.modules.clear()
